<template>
  <div id="qiRptFiled">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" :loading="showLoading" @click="findqiIndexIMainList(qiIndexId)"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-square-plus" class="button-blue" content="新增" @click="handleAdd(-1)"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-save" class="button-blue" content="保存" @click="saveList"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="qiRptFiledTable">
      <vxe-table ref="qiRptFiledTableRef" :loading="showLoading" class="mytable-scrollbar" align="left" border height="auto" :keep-source="true" :data="qiIndexIMainList" @cell-click="qiIndexItemRowClick" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
        <vxe-column type="checkbox" align="center" width="26"></vxe-column>
        <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
        <vxe-column field="itemCode" title="项目编码" min-width="80px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.itemCode" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="itemName" title="项目名称" width="820px" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.itemName" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="seq" title="顺序" min-width="40" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="text"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <vxe-modal v-model="showItemCondition" title="数据条件" width="900" height="500" :mask="false" :lock-view="false" resize @close="closeItemConditionModal">
      <template #default>
        <div class="modalBox">
          <vxe-radio-group v-model="majorName" @change="changeMajor">
            <div style="float: left" v-for="(p, pindex) in qiIndexMajorList" :key="pindex">
              <vxe-radio-button :label="p.id" :content="p.majorName"></vxe-radio-button>
            </div>
          </vxe-radio-group>
          <div class="textareaBox">
            <!-- <el-container>
              <el-main> -->
            <el-form ref="indexConditionFormRef" :model="indexConditionForms[currentMajorIndex]" class="form-input-m" :inline-message="true">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="itemCondition">
                    <span class="textareaTitle">项目:{{ '【' + currentItemName + '】' }}</span>
                    <vxe-textarea v-model="indexConditionForms[currentMajorIndex].itemCondition" class="textareaItem" placeholder="项目条件" resize="none"></vxe-textarea>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="majorCondition">
                    <span class="textareaTitle">专业:{{ '【' + currentMajorName + '】' }}</span>
                    <vxe-textarea v-model="indexConditionForms[currentMajorIndex].majorCondition" class="textareaItem" placeholder="专业条件" resize="none"></vxe-textarea>
                  </el-form-item>
                </el-col>
              </el-row>
              <span class="textareaTitle">合并结果</span>
              <el-form-item prop="mergeCondition">
                <vxe-textarea v-model="indexConditionForms[currentMajorIndex].mergeCondition" class="textareaItem" placeholder="可以调节高度" resize="vertical"></vxe-textarea>
              </el-form-item>
            </el-form>
            <div class="dialog-footer justify-end flex">
              <el-button type="primary" @click="handleSave()">保 存</el-button>
              <el-button @click="clearForm()">重 置</el-button>
            </div>
            <!-- </el-main>
            </el-container> -->
          </div>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, defineExpose } from 'vue';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// 全局变量定义区 ==========
defineExpose({
  findqiIndexIMainList,
  getQiIndexMajorList
});

interface RowVO {
  id: string;
  itemCode: string;
  itemName: string;
  seq: number; //顺序号
  indexId: string;
  qidxId: string;
}

let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //刷新+表格加载状态
const qiIndexIMainList = reactive([]);
const qiIndexMajorList = reactive([]);
let qiIndexId = ref(null);
const qiRptFiledTableRef = ref(null);
let showItemCondition = ref(false);
const majorName = ref('');
const indexConditionForms = reactive([]);
let currentItemName = ref('');
let currentMajorName = ref('');
let currentMajorIndex = ref(0);

// 方法定义区 =============
onMounted(() => { });

// 获取列表
function findqiIndexIMainList(qiIndex: any) {
  showLoading.value = true;
  qiIndexId.value = qiIndex;
  qiIndexIMainList.length = 0; //放入数据前清空数据
  const url = '/api/qi/reportFiled/getQiIndexItemList/' + qiIndexId.value;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        qiIndexIMainList.push(...res.data);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}
// 获取专业信息
function getQiIndexMajorList(qiIndex: any) {
  showLoading.value = true;
  qiIndexId.value = qiIndex;
  qiIndexMajorList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiIndexMajor/getIndexMajorList/' + qiIndexId.value;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data) && res.data.length > 0) {
        qiIndexMajorList.push(...res.data);
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}
// 点击表格当前行
function qiIndexItemRowClick({ row }: any) {
  indexConditionForms.length = 0;
  // ToDo
  currentItemName.value = row.itemName;
  if (qiIndexMajorList.length > 0) {
    majorName.value = qiIndexMajorList[0].id;
    currentMajorName.value = qiIndexMajorList[0].majorName;
    qiIndexMajorList.forEach((item) => {
      let majorObj = {
        id: '',
        indexId: row.indexId,
        itemId: row.id,
        itemName: row.itemName,
        majorId: item.id,
        majorName: item.majorName,
        itemCondition: '',
        majorCondition: '',
        mergeCondition: ''
      };
      indexConditionForms.push(majorObj);
    });
    const url = '/api/qi/indexCond/getIndexConditionList/' + row.id;
    proxy.$http
      .get(url)
      .then((res: any) => {
        if (!IsEmpty(res.data) && res.data.length > 0) {
          indexConditionForms.length = 0;
          indexConditionForms.push(...res.data);
        }
        showLoading.value = false;
        showItemCondition.value = true;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        showLoading.value = false;
      });
  }
}

// 点击专业
function changeMajor(radioObj: any) {
  let qiIndexMajorObj = qiIndexMajorList.find((item) => item.id === radioObj.label);
  currentMajorIndex.value = qiIndexMajorList.findIndex((item) => item.id === radioObj.label);
  currentMajorName.value = qiIndexMajorObj.majorName;
}
//新增
async function handleAdd(row?: RowVO | number) {
  const $table = proxy.$refs.qiRptFiledTableRef as any;
  if ($table) {
    const record = {
      id: null,
      itemCode: '',
      itemName: '',
      seq: '', //顺序号
      indexId: qiIndexId,
      qidxId: null
    };
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditRow(newRow);
  }
}

//批量保存
function saveList() {
  const $table = proxy.$refs.qiRptFiledTableRef as any;
  const arrNews = $table.getInsertRecords();
  const arrModifies = $table.getUpdateRecords();
  arrNews.forEach((item: any, idx) => {
    const url = '/api/qi/reportFiled/addQiIndexItem';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findqiIndexIMainList(qiIndexId.value);
        }
      })
      .catch((err) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
  arrModifies.forEach((item, idx) => {
    const url = '/api/qi/reportFiled/updateQiIndexItem';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findqiIndexIMainList(qiIndexId.value);
        }
      })
      .catch((err) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
}
//删除
function handleDelete() {
  const $xTable = proxy.$refs.qiRptFiledTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        selectRows.forEach((item, idx) => {
          const url = '/api/qi/reportFiled/deleteQiIndexItem';
          proxy.$http
            .post(url, item)
            .then((res: any) => {
              if (idx === selectRows.length - 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findqiIndexIMainList(qiIndexId.value);
              }
            })
            .catch((err) => {
              VxeMessage('删除时出现异常', VxeNotifyType.error);
            });
        });
      }
    });
}

// 保存条件
function handleSave() {
  let url = '';
  if (indexConditionForms.length > 0 && indexConditionForms[0].id) {
    url = '/api/qi/indexCond/updateQiIndexCondition';
  } else {
    url = '/api/qi/indexCond/addQiIndexConditions';
  }
  proxy.$http
    .post(url, indexConditionForms)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('保存成功！', VxeNotifyType.success);
      } else {
        VxeMessage('保存失败！', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}

// 清空条件表单部分信息
function clearForm() {
  const conditionArr = ['itemCondition', 'majorCondition', 'mergeCondition'];
  conditionArr.forEach((key) => {
    if (typeof indexConditionForms[currentMajorIndex.value][key] === 'string') {
      indexConditionForms[currentMajorIndex.value][key] = '';
    }
  });
}
</script>

<style lang="scss" scoped>
#qiRptFiled {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .qiRptFiledTable {
    height: calc(100% - 40px);
  }
  .modalBox {
    height: 100%;
    .textareaBox {
      margin-top: 10px;
      height: calc(100% - 24px - 10px);
      .textareaTitle {
        font-size: 14px;
      }
      .textareaItem {
        width: 100%;
        height: 150px;
        :deep(.vxe-textarea--inner) {
          height: 100%;
        }
      }
    }
  }
}
</style>
